package ru.hh.team02.chat.messaging;

import java.util.Set;

import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.server.ChatServer;
import ru.hh.team02.chat.utils.HashMapWithLock;

/**
 * class responsible for macro sending logic.
 * current version - one queue with messages per active client
 */
public class SendingService {
    private static final int WORKING_THREADS = 1; 
    
    private HashMapWithLock<String, SendingQueue> queues = 
            new HashMapWithLock<String, SendingQueue>();
    
    /**
     * given client name, add his personal queue
     */
    public void addQueue(String name) {
        try {
            queues.getLock().writeLock().lock();
            queues.put(name, new SendingQueue(WORKING_THREADS));
        } finally {
            queues.getLock().writeLock().unlock();
        }
    }
    
    /**
     * given client name, stop his personal queue
     * and delete it
     */
    public void removeQueue(String name) {
        try {
            queues.getLock().writeLock().lock();
            assert(queues.containsKey(name));
            queues.get(name).stop();
            queues.remove(name);
        } finally {
            queues.getLock().writeLock().unlock();
        }
    }

    /**
     * Put the message for sending in the queue.
     * The addressee is already encapsulated inside the message.
     * @param message
     */
//    public static void sendMessage(Message message) {
//        sendingQueue.add(message);
//    }

    /**
     * Put message to all personal queues of people, 
     * who are in the same room as sender
     * @param text Message text
     * @param name Sender name
     */
    public void sendMessageToRoom(String text, String senderName) {
        String room = ChatServer.registry.getClientRoom(senderName);
        Set<Client> recepients = ChatServer.registry.getClientsFromRoom(room);

        try {
            queues.getLock().readLock().lock();
            for (Client recepient : recepients) {
                Message message = new Message(text, recepient);
                queues.get(recepient.getName()).add(message);
            }             
        } finally {
            queues.getLock().readLock().unlock();
        }
      
    }
}
